package com.ks.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ks.entity.User;
import com.ks.listener.UserSessionListener;
import com.ks.utils.CookieUtils;

import common.Var;

@WebServlet("/logout")
public class LoginOutServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Log log = LogFactory.getLog(LoginOutServlet.class);

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			HttpSession session = request.getSession(false);
			if (session == null) {
				throw new RuntimeException("用户没有登录！");
			}
			delSession(session);
			session.removeAttribute(Var.USER_INFO);// 清空session信息
			session.invalidate();// 清除 session 中的所有信息
			// 退出登录的时候清空cookie信息,cookie需要通过HttpServletRequest，HttpServletResponse获取
			CookieUtils.deleteCookieNow(request, response);
			response.sendRedirect("/index.html");
//		PrintWriter out = response.getWriter();
			/** 前后端分离返回Ajax */
//		out.print("注销成功");
		} catch (Exception e) {
			log.error("注销用户失败！", e);
		}

	}

	/**
	 * @Description 删除单一登录中记录用户单一登录变量中的session
	 * @param session
	 */
	private synchronized void delSession(HttpSession session) {

		if (session != null && session.getAttribute(Var.USER_INFO) != null) {
			User user = (User) session.getAttribute(Var.USER_INFO);
			UserSessionListener.sessionMap.remove(user.getUsername());
		}
	}

}
